<?php
/* MyMeeting is an online meeting management software.
 * Copyright (C) 2009 Government Of Malaysia
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * @author: Abdullah Zainul Abidin, Nuhaa All Bakry
 *          Eavay Javay Barnad, Sarogini Muniyandi, Teow Jit Huan
 *
 */

class GroupstatusesController extends AppController {

    /**
     * Define $name
     *
     */
    var $name = 'Groupstatuses';
    /**
     * Define $helpers
     *
     */
    var $helpers = array('Html', 'Form', 'DatePicker','Comment','MultiFile');
    /**
     * Define $components
     *
     */
    var $components = array('MultiFile');
    /**
     * Define $uses
     *
     */
    var $uses = array ('Notification','Comment','Template','Groupstatus','Attachment');

    /**
     * Describe index
     *
     * @param $committee
     * @return null
     */
    function index($committee) {
        $dcommittee=$this->Groupstatus->Decision->Meeting->Committee->findByShortName($committee);
        $this->set('dcommittee',$dcommittee);
        $this->Groupstatus->recursive = 0;
        $this->set('groupStatuses', $this->paginate());
    }

    /**
     * Describe view
     *
     * @param $committee
     * @param $id
     * @return null
     */
    function view($committee,$id = null) {
        $dcommittee=$this->Groupstatus->Decision->Meeting->Committee->findByShortName($committee);
        $this->set('dcommittee',$dcommittee);
        if (!$id) {
            $this->Session->setFlash(__('Invalid Groupstatus.', true));
            $this->redirect(array('action'=>'index'));
        }
        $this->set('groupStatus', $this->Groupstatus->read(null, $id));
    }

    /**
     * Describe add
     *
     * @param $committee
     * @return null
     */
    function add($committee) {
        $this->Groupstatus->Decision->Meeting->Committee->unbindModel(array('hasMany'=>array('Announcement','Item','Group','Meeting','Decision','Todo','Userstatus','Groupstatus','Workflow','Wfmodel'),'hasAndBelongsToMany'=>array('User','Membership')),false);
        $this->Groupstatus->Decision->Behaviors->detach('MultiFile');
        $this->Groupstatus->Decision->Behaviors->detach('Comment');
        $this->Groupstatus->Decision->unbindModel(array('hasMany'=>array('Userstatus','Groupstatus')),false);
        
        $this->set('dcommittee',$this->dcommittee);
        if (!empty($this->data)) {
            $this->Groupstatus->create();
            $this->data['Groupstatus']['user_id']=$this->Auth->user('id');
            $this->data['Groupstatus']['committee_id']=$this->dcommittee['Committee']['id'];
            if ($this->Groupstatus->save($this->data)) {
				$this->Session->setFlash(__('The Groupstatus has been saved', true));
                if(configure::read('e_updatestatus')==1){
                    $groupstatus=$this->Groupstatus->findById($this->Groupstatus->getLastInsertID());
                    $this->redirect(array('committee'=>$committee,'decisionid'=>$groupstatus['Groupstatus']['decision_id'],'action'=>'informupdate',$id=$groupstatus['Groupstatus']['group_id']));
                }else{
                    $this->redirect(array('committee'=>$committee,'controller'=>'decisions','action'=>'view','id'=>$this->data['Groupstatus']['decision_id']));
                }
            } else {
                $this->Session->setFlash(__('The Groupstatus could not be saved. Please, try again.', true));
            }
        }
        $oldstatus=$this->Groupstatus->find('first',array(
            'conditions'=>array(
                'decision_id'=>$this->params['decisionid'],
                'group_id'=>$this->params['group_id'],
                'Groupstatus.deleted'=>0,
            ),
            'order'=>array(
                'Groupstatus.updated desc',
            ),
        ));
        $this->data = $oldstatus;

        $this->set('returnpage',$this->referer(null,true));
        
        $decision = $this->Groupstatus->Decision->find('first',array(
            'conditions'=>array('Decision.id'=>$this->params['decisionid']),
            'order'=>'Decision.created DESC'
            ));
            
        //check permission
        if($this->Auth->user('superuser')==0){
            $sec=$this->Groupstatus->Decision->Meeting->Attendance->isSecretariat($decision['Decision']['meeting_id'],$this->Auth->user('id'));
            if(empty($sec)){
                if($this->permission['Groupstatus']['Create']){
                }elseif(!$this->Groupstatus->Group->UsersGroup->find('count',array('conditions'=>array('UsersGroup.group_id'=>$this->params['group_id'],'UsersGroup.user_id'=>$this->Auth->user('id'))))){
                    $this->notpermit();
                }
            }
        }
        
        $this->set('decision',$decision);
    }

    /**
     * Create notifications when comments are made to the status
     *
     * @param $status_id 
     * @param $comment_id
     * @return null
     */
    function sendcomment($status_id,$comment_id){
		$this->Groupstatus->Behaviors->detach('Comment');
        $this->Groupstatus->Decision->Meeting->Behaviors->detach('Comment');
        //insert needed data for template
        $status=$this->Groupstatus->read(null,$status_id);
        $comment=$this->Comment->read(null,$comment_id);
		$status['Comment']['comment']=$comment['Comment']['description'];
        $status['Comment']['user']=$this->Auth->user('name');
        $status['Link']['decision']=array('committee'=>urlencode($status['Committee']['short_name']),'controller'=>'decisions','action'=>'view','id'=>$status['Groupstatus']['decision_id']);
        $status['Status']=$status['Groupstatus'];
        $status=am($status,$this->Groupstatus->Decision->Meeting->find('first',array('contain'=>false,'conditions'=>array('id'=>$status['Decision']['meeting_id']))));
        $template=$this->Template->processTemplate('status comment',$status);
        // find the recipient
        $usersids=set::extract(
            $this->Groupstatus->Decision->Meeting->User->Group->UsersGroup->find('all',array(
                'conditions'=>array('group_id'=>$status['Groupstatus']['group_id'])
            )),
        '{n}.UsersGroup.user_id');
        foreach($usersids as $userid){
            $user=$this->Groupstatus->Decision->Meeting->User->findById($userid);
            $this->Groupstatus->Decision->Meeting->sendEmail($status['Meeting'],$template,$user['User'],null);
        }
		$this->redirect(array('committee'=>$this->dcommittee['Committee']['short_name'],'controller'=>'decisions','action'=>'view','id'=>$status['Groupstatus']['decision_id']));
    }

    /**
     * Describe edit
     *
     * @param $committee
     * @param $id
     * @return null
     */
    function edit($committee,$id = null) {
        $this->set('dcommittee',$this->dcommittee);
		$meeting_id=$this->Groupstatus->Decision->Meeting->getLastInsertID();
        if (!$id && empty($this->data)) {
            $this->Session->setFlash(__('Invalid Groupstatus', true));
            $this->redirect(array('action'=>'index'));
        }
        if (!empty($this->data)) {
			$this->data['Groupstatus']['user_id']=$this->Auth->user('id');
            $this->data['Groupstatus']['committee_id']=$this->dcommittee['Committee']['id'];
            $this->Groupstatus->curUser=$this->Auth->user('id');
            if ($this->Groupstatus->save($this->data)) {
                if(!isset($this->data['Groupstatus']['id'])){
                    $newid=$this->Groupstatus->getLastInsertID();
                    $oldstatus=$this->Groupstatus->find('first',array(
                        'conditions'=>array(
                            'decision_id'=>$this->data['Groupstatus']['decision_id'],
                            'group_id'=>$this->data['Groupstatus']['group_id'],
                            'Groupstatus.deleted'=>0,
                            'Groupstatus.id<'.$newid,
                        ),
                        'order'=>array(
                            'Groupstatus.updated desc',
                        ),
                    ));
                    $attachments=$this->Attachment->find('all',array(
                        'conditions'=>array(
                            'foreign_key'=>$oldstatus['Groupstatus']['id'],
                            'model'=>'Groupstatus',
                        ),
                    ));
                    foreach($attachments as $attachment){
                        $attachment['Attachment']['foreign_key']=$newid;
                        $this->Attachment->save($attachment);
                    }
                }
                else{
                    $newid=$this->data['Groupstatus']['id'];
                }
                if(isset($this->data['Groupstatus']['returnpage'])){
                    if(isset($this->data['GroupstatusComment']['Comment']) ){
                        if(configure::read('e_statuscomment')==1){
                            $this->Comment=ClassRegistry::init('Comment','model');
                            $this->sendcomment($this->data['Groupstatus']['id'],$this->Comment->getLastInsertID());
                        }else{
                            $this->Session->setFlash(__('The Groupstatus has been saved', true));
                        }
                    }elseif(configure::read('e_updatestatus')==1){
						$groupstatus=$this->Groupstatus->findById($newid);
						$this->redirect(array('committee'=>$committee,'decisionid'=>$groupstatus['Groupstatus']['decision_id'],'action'=>'informupdate',$id=$groupstatus['Groupstatus']['group_id']));
                    }
                    $this->redirect($this->data['Groupstatus']['returnpage'].'#group'.$newid);
                }
                else{
                    $this->redirect(array('action'=>'index'));
                }
            } else {
                $this->Session->setFlash(__('The Groupstatus could not be saved. Please, try again.', true));
            }
        }
        if (empty($this->data)) {
            $this->data = $this->Groupstatus->read(null, $id);
        }
        $decisions = $this->Groupstatus->Decision->find('list');
        $users = $this->Groupstatus->User->find('list');
        $groups = $this->Groupstatus->Group->find('list');
        $this->set(compact('decisions','users','groups'));
    }

    /**
     * Describe delete
     *
     * @param $committee
     * @param $id
     * @return null
     */
    function delete($committee,$id = null) {
        $dcommittee=$this->Groupstatus->Decision->Meeting->Committee->findByShortName($committee);
        $this->set('dcommittee',$dcommittee);
        if (!$id) {
            $this->Session->setFlash(__('Invalid id for Groupstatus', true));
            $this->redirect(array('action'=>'index'));
        }
        $this->Groupstatus->del($id);
        $this->Session->setFlash(__('Groupstatus deleted', true));
        $this->redirect(array('action'=>'index'));
    }


    function view_history($committee,$decisionid = null,$id=null) {
        
        $dcommittee=$this->Groupstatus->Decision->Meeting->Committee->findByShortName($committee);
        $this->set('dcommittee',$dcommittee);

        Configure::write('debug', 0); // dont want debug in ajax returned html
        $this->layout="popup";
        
        $statuses = $this->Groupstatus->find('all',array('conditions'=>array('Committee.id'=>$dcommittee['Committee']['id'],'Decision.id'=>$decisionid,'Group.id'=>$id),'order'=>'Groupstatus.created DESC'));
        
        foreach($statuses as $sid=>$status){
            $comment=$this->Comment->find('all',array('conditions'=>array('model'=>'Groupstatus','foreign_key'=>$status['Groupstatus']['id']),'order'=>'updated desc'));
            
            if(count($comment)){
                foreach($comment as $cid=>$curcomment){
                    $users=$this->Groupstatus->User->find('first',array('fields'=>array('name','job_title'),'conditions'=>array('User.id'=>$curcomment['Comment']['user_id'])));
                    $comment[$cid]['Comment']['user_name']=$users['User']['name'];
                    $comment[$cid]['Comment']['job_title']=$users['User']['job_title'];
                }
                $statuses[$sid]['Groupstatus']['GroupstatusComment']=$comment;
            }
        }
        $this->set('statuses',$statuses);
	}
	
		
	function informupdate($committee,$decisionid,$id){
        $this->Groupstatus->Behaviors->attach('Containable');
        $groupstatus=$this->Groupstatus->find('first',array('conditions'=>array('Committee.id'=>$this->dcommittee['Committee']['id'],'Decision.id'=>$decisionid,'Group.id'=>$id),'order'=>'Groupstatus.created DESC'));
        $groupstatus=am($groupstatus,$this->Groupstatus->Decision->Meeting->find('first',array('contain'=>false,'conditions'=>array('id'=>$groupstatus['Decision']['meeting_id']))));
        $groupstatus['Status']=$groupstatus['Groupstatus'];
        $groupstatus['Status']['user']=$groupstatus['Group']['name'];
        $groupstatus['Updater']=$this->Auth->user('name');
        $groupstatus['Link']['decision']=array('committee'=>urlencode($this->dcommittee['Committee']['short_name']),'controller'=>'decisions','action'=>'view','decisionid'=>$decisionid);
        $template=$this->Template->processTemplate('update status',$groupstatus);
        $template['Template']['template']=str_replace(array('%%content to repeat','content to repeat%%'),'',$template['Template']['template']);
        if($template){
            $secretariat=$this->Groupstatus->Decision->Meeting->Attendance->find('all',array('conditions'=>array('Attendance.attend_as'=>1,'Attendance.meeting_id'=>$groupstatus['Meeting']['id'])));
            if(!empty($secretariat)){
                foreach ($secretariat as $sec){
                    $this->Groupstatus->Decision->Meeting->sendEmail($groupstatus['Meeting'],$template,$sec['User'],null);
                }
                $this->Session->setFlash(__('The notification of updating status has been sent to secretariat', true));
            }else{
                $this->Session->setFlash(__('The status has been saved', true));
            }
        }
		$this->redirect(array('committee'=>$committee,'controller'=>'decisions','action'=>'view','id'=>$decisionid));
    }
				
}

?>
